// src/components/calendar/Calendar.jsx
import React, { useEffect, useState } from 'react';
import { getItem, setItem } from '../../utils/localStorage';
import { useAuth } from '../../contexts/AuthContext';

const Calendar = () => {
  const [events, setEvents] = useState([]);
  const [selectedDate, setSelectedDate] = useState(new Date());
  const { user } = useAuth();

  useEffect(() => {
    // Initialize calendar events if they don't exist
    const storedEvents = JSON.parse(getItem('calendar_events') || '[]');
    if (storedEvents.length === 0) {
      const initialEvents = [
        {
          id: 1,
          title: '速度之王挑战赛',
          description: '在上海国际赛道参加速度挑战',
          date: '2024-03-15',
          track: '上海国际赛道',
          type: 'challenge',
          participants: 12
        },
        {
          id: 2,
          title: 'GT3赛车体验',
          description: '预订Ferrari 488 GT3赛车',
          date: '2024-03-20',
          track: '珠海国际赛道',
          type: 'booking',
          vehicle: 'Ferrari 488 GT3'
        }
      ];
      setItem('calendar_events', JSON.stringify(initialEvents));
      setEvents(initialEvents);
    } else {
      setEvents(storedEvents);
    }
  }, []);

  const getDaysInMonth = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const days = [];
    
    // Add empty days for padding
    for (let i = 0; i < firstDay.getDay(); i++) {
      days.push(null);
    }
    
    // Add all days in month
    for (let i = 1; i <= lastDay.getDate(); i++) {
      days.push(new Date(year, month, i));
    }
    
    return days;
  };

  const days = getDaysInMonth(selectedDate);

  const getEventsForDate = (date) => {
    if (!date) return [];
    return events.filter(event => {
      const eventDate = new Date(event.date);
      return eventDate.toDateString() === date.toDateString();
    });
  };

  const handlePrevMonth = () => {
    setSelectedDate(new Date(selectedDate.getFullYear(), selectedDate.getMonth() - 1));
  };

  const handleNextMonth = () => {
    setSelectedDate(new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1));
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-900">赛事日历</h1>
        <div className="flex items-center space-x-4">
          <button
            onClick={handlePrevMonth}
            className="p-2 hover:bg-gray-100 rounded-full"
          >
            ←
          </button>
          <span className="text-lg font-medium">
            {selectedDate.getFullYear()}年{selectedDate.getMonth() + 1}月
          </span>
          <button
            onClick={handleNextMonth}
            className="p-2 hover:bg-gray-100 rounded-full"
          >
            →
          </button>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow-md overflow-hidden">
        <div className="grid grid-cols-7 text-center border-b">
          {['日', '一', '二', '三', '四', '五', '六'].map((day) => (
            <div key={day} className="py-2 font-medium text-gray-600">
              {day}
            </div>
          ))}
        </div>
        <div className="grid grid-cols-7">
          {days.map((date, index) => (
            <div
              key={index}
              className={`min-h-[100px] p-2 border-t border-r ${
                date ? 'bg-white' : 'bg-gray-50'
              }`}
            >
              {date && (
                <>
                  <div className="font-medium text-gray-900">
                    {date.getDate()}
                  </div>
                  <div className="space-y-1 mt-1">
                    {getEventsForDate(date).map((event) => (
                      <div
                        key={event.id}
                        className={`text-xs p-1 rounded ${
                          event.type === 'challenge'
                            ? 'bg-red-100 text-red-800'
                            : 'bg-blue-100 text-blue-800'
                        }`}
                      >
                        {event.title}
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Calendar;